#!/usr/bin/env python
# _*_coding:utf-8_*_


import os
import time
import serial
import serial.tools.list_ports


def init_serial(com_address_in, baudrate=115200, bytesize=8, parity=serial.PARITY_NONE, stopbits=1):
    serial_instance = serial.Serial(com_address_in, baudrate, bytesize, parity, stopbits)
    return serial_instance


def get_com_list():
    port_list = list(serial.tools.list_ports.comports())
    com_list = []
    if port_list:
        for n, (port, desc, hwid) in enumerate(sorted(port_list), 1):
            com_list.append(port + "," + desc)
        return com_list


def write(serial_session_in, serial_command_in, termination_char_in='\n', debug_serial_in=False):
    """
    Sends a Standard Commands for Programmable Instruments  command to the instrument defined by the SCPI session
    :param termination_char_in:  The termination character used by the instrument
    :param serial_session_in: The Serial session to send the command to
    :param serial_command_in:: The Serial command to send
    :param debug_serial_in: If True, # prints the sent command
    :return:
    """

    # # print the input if debug
    if debug_serial_in:
        print('Debug Serial Command Sent: ' + serial_command_in)
    # Add the newline
    serial_session_in.write((serial_command_in + termination_char_in).encode("utf-8"))
    return


def close(serial_session_in):
    serial_session_in.close()


class SwitchDriver:
    def __init__(self, com_address_in, connect_in=True, debug_serial_in=False):
        # Start a session
        self.__is_connected = False
        self.__com_address = com_address_in

        self.__debug_mode = debug_serial_in
        if connect_in:
            self.__serial_session = init_serial(com_address_in=com_address_in)
            self.__is_connected = True

    def close(self):
        cmd = "1J"
        # cmd = "1D"
        write(self.__serial_session, cmd)
        time.sleep(0.2)

    def open(self):
        cmd = "2J"
        # cmd = "2D"
        write(self.__serial_session, cmd)
        time.sleep(0.2)

    def close_com(self):
        if self.__serial_session.isOpen():
            self.__serial_session.close()


# inst = SwitchDriver("COM6")
# time.sleep(2)
# inst.close()
# time.sleep(5)
# inst.open()

